package searchkeyword

import (
	"context"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateSearchKeywordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateSearchKeywordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateSearchKeywordLogic {
	return &CreateSearchKeywordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateSearchKeywordLogic) CreateSearchKeyword(req *types.CreateSearchKeywordReq) (*types.BaseMsgResp, error) {
	if req.StartedAt == nil || len(strings.TrimSpace(*req.StartedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "searchkeyword.startedAtRequired"))
	}

	if req.EndedAt == nil || len(strings.TrimSpace(*req.EndedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "searchkeyword.endedAtRequired"))
	}

	var searchKeywordType *uint32
	if req.Type != nil && *req.Type > 0 {
		//搜索词类型：常驻词/热门词  默认常驻词
		searchKeywordType = req.Type
	} else {
		searchKeywordType = pointy.GetPointer(uint32(globalkey.SettingSearchKeywordTypeRecommend))
	}
	var objectId *uint64
	var objectType *uint32
	if req.LinkType != nil && *req.LinkType > 0 { // 相对路径，接收广告类型和广告ID
		objectType = req.ObjectType
		objectId = req.ObjectId
	}

	res, err := l.svcCtx.BackendRpc.CreateSearchKeyword(l.ctx, &backendclient.SearchKeywordInfo{
		Type:       searchKeywordType,
		Title:      req.Title,
		LinkType:   req.LinkType,
		LinkUrl:    req.LinkUrl,
		ObjectType: objectType,
		ObjectId:   objectId,
		Status:     req.Status,
		Sort:       req.Sort,
		StartedAt:  req.StartedAt,
		EndedAt:    req.EndedAt,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
